package com.coder.baseapp.injecter.module;

import android.content.Context;
import android.util.Log;

import com.coder.baseapp.App;
import com.coder.baseapp.common.Constants;
import com.coder.baseapp.mvp.model.API;

import java.io.File;
import java.io.IOException;
import java.util.Locale;
import java.util.concurrent.TimeUnit;

import javax.inject.Singleton;

import dagger.Module;
import dagger.Provides;
import okhttp3.Cache;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

import static android.content.ContentValues.TAG;

/**
 * Application Module
 *
 * @Author: Tua.CoderGui
 * *
 * @Date: 2017/3/10
 * *
 * Copyright (c) 2017 All Rights Reserved.
 */
@Module
public class ApplicationModule {

    //设缓存大小
    private static final long CACHE_SIZE = 1024 * 1024 * 100;

    //设缓存有效期为1天
    private static final long CACHE_STALE_SEC = 60 * 60 * 24 * 1;

    //查询缓存的Cache-Control设置，为if-only-cache时只查询缓存而不会请求服务器，max-stale可以配合设置缓存失效时间
    private static final String CACHE_CONTROL_CACHE = "only-if-cached, max-stale=" + CACHE_STALE_SEC;

    private final App mApp;

    public ApplicationModule(App application) {
        mApp = application;
    }

    /**
     * 提供context
     *
     * @return
     */
    @Provides
    @Singleton
    public Context provideApplicationContext() {
        return mApp.getApplicationContext();
    }


    /**
     * 提供通用api
     *
     * @param retrofit
     * @return
     */
    @Provides
    @Singleton
    public API provideApi(Retrofit retrofit) {
        return retrofit.create(API.class);
    }

    /**
     * 提供Retrofit
     *
     * @param client okhttp
     * @return
     */
    @Provides
    @Singleton
    public Retrofit provideRetrofit(OkHttpClient client) {
        return new Retrofit.Builder()
                .baseUrl(Constants.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(client)
                .build();
    }

    @Provides
    @Singleton
    public OkHttpClient provideOkHttpClient(Context context) {

        Cache cache = new Cache(new File(context.getCacheDir(), "HttpCache"), CACHE_SIZE);
        OkHttpClient okHttpClient = new OkHttpClient.Builder().cache(cache)
                .addInterceptor(createLogginInterceptor())
                .connectTimeout(10, TimeUnit.SECONDS)
                .build();
        return okHttpClient;
    }

    /**
     * 打印返回的json数据拦截器
     */
    private Interceptor createLogginInterceptor() {
        return new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request request = chain.request();
                Log.v(TAG, "request:" + request.toString());
                long t1 = System.nanoTime();
                okhttp3.Response response = chain.proceed(chain.request());
                long t2 = System.nanoTime();
                Log.v(TAG, String.format(Locale.getDefault(), "Received response for %s in %.1fms%n%s",
                        response.request().url(), (t2 - t1) / 1e6d, response.headers()));
                okhttp3.MediaType mediaType = response.body().contentType();
                String content = response.body().string();
                Log.i(TAG, "response body:" + content);
                return response.newBuilder()
                        .body(okhttp3.ResponseBody.create(mediaType, content))
                        .build();
            }
        };
    }
}
